/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sacodemel.financeiro.servico.impl;

import com.sacodemel.financeiro.modelo.Colheita;
import com.sacodemel.financeiro.modelo.Pessoa;
import com.sacodemel.financeiro.modelo.RegistroCaixa;
import com.sacodemel.financeiro.persistencia.dao.impl.SegurancaDAO;
import com.sacodemel.financeiro.persistencia.dao.ISegurancaDAO;
import com.sacodemel.financeiro.persistencia.dao.impl.BaseDAO;
import com.sacodemel.financeiro.servico.IColheitasService;
import com.sacodemel.financeiro.servico.IFluxoDeCaixaService;
import com.sacodemel.financeiro.servico.IInvestidoresService;
import com.sacodemel.financeiro.servico.ISegurancaService;
import com.thoughtworks.xstream.XStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.inject.Named;

/**
 *
 * @author X4Q1
 */
@Named
public class SegurancaService implements ISegurancaService {

    ISegurancaDAO seg = new SegurancaDAO();

    @Override
    public boolean isConexaoOk() {
        return seg.isConexaoOk();
    }

    private List<File> retornaArquivosXML() {
        XStream xstream = new XStream();
        List<File> arquivosBackup = new ArrayList<File>();

        try {

            arquivosBackup.add(retornaArquivoPessoa(xstream));
            arquivosBackup.add(retornaArquivoColheita(xstream));
            arquivosBackup.add(retornaArquivoRegistroCaixa(xstream));

        } catch (Exception ex) {
            Logger.getLogger(SegurancaService.class.getName()).log(Level.SEVERE, null, ex);
        }


        return arquivosBackup;
    }

    private File retornaArquivoPessoa(XStream xstream) throws IOException, Exception {

        IInvestidoresService invest = new InvestidoresService();
        File pessoa = new File("pessoa.xml");
        FileWriter x = new FileWriter(pessoa, false);
        xstream.alias("pessoa", Pessoa.class);
        x.write(xstream.toXML(invest.obterListaTodosInvestidores()));
        x.close();

        return pessoa;
    }

    private File retornaArquivoColheita(XStream xstream) throws IOException, Exception {

        IColheitasService colheitaServ = new ColheitasService();
        File colheita = new File("colheita.xml");
        FileWriter x = new FileWriter(colheita, false);
        xstream.alias("colheita", Colheita.class);
        x.write(xstream.toXML(colheitaServ.obterListaTodasColheitas()));
        x.close();

        return colheita;
    }

    private File retornaArquivoRegistroCaixa(XStream xstream) throws IOException, Exception {

        IFluxoDeCaixaService fluxoServ = new FluxoDeCaixaService();
        File colheita = new File("registro.xml");
        FileWriter x = new FileWriter(colheita, false);
        xstream.alias("registro", RegistroCaixa.class);
        x.write(xstream.toXML(fluxoServ.obterTodosRegistros()));
        x.close();
       

        return colheita;
    }

    private File retornaArquivoZIP(List<File> arqEntrada) throws IOException {
        int cont;
        int TAMANHO_BUFFER = 4096;


        BufferedInputStream origem = null;
        FileInputStream streamDeEntrada = null;
        FileOutputStream destino = null;
        ZipOutputStream saida = null;
        ZipEntry entry = null;

        try {

            File arquivoZip = new File("backup.zip");

            destino = new FileOutputStream(arquivoZip);
            saida = new ZipOutputStream(new BufferedOutputStream(destino));

            for (File f : arqEntrada) {

                byte[] dados = new byte[TAMANHO_BUFFER];

                streamDeEntrada = new FileInputStream(f);
                origem = new BufferedInputStream(streamDeEntrada, TAMANHO_BUFFER);
                entry = new ZipEntry(f.getName());
                saida.putNextEntry(entry);

                while ((cont = origem.read(dados, 0, TAMANHO_BUFFER)) != -1) {
                    saida.write(dados, 0, cont);
                }

            }

            origem.close();
            saida.close();

            return arquivoZip;

        } catch (IOException e) {
            throw new IOException(e.getMessage());
        }
    }

    public void gerarArquivosBackup(OutputStream output) throws IOException {

        File file = retornaArquivoZIP(this.retornaArquivosXML());

        FileInputStream in = new FileInputStream(file);

        byte[] buf = new byte[(int) file.length()];
        int count;
        while ((count = in.read(buf)) >= 0) {
            output.write(buf, 0, count);
        }

        in.close();

        output.flush();
        output.close();

    }
}
